//定义用户相关的仓库
import { defineStore } from "pinia";
import { reqUSERCODE, reqLogin } from "@/api/hospital";
import { LoginData, UserLoginResponseData, UserInfo } from '@/api/hospital/type';
import type { UserState } from "./moduls/interface";
import { GET_TOKEN, SET_TOKEN, REMOVE_TOKEN } from "@/utils/user";
const useUserStore = defineStore('user', {
    state: (): UserState => {
        return {
            visable: false,//用于控制dialog控件显示与隐藏
            UserCode: "",
            UserInfo: JSON.parse(GET_TOKEN() as string) || {}
        }
    },
    actions: {
        //获取验证码
        async getCode(phone: string) {
            let result: any = await reqUSERCODE(phone);
            if (result.code == 200) { this.UserCode = result.data; return 'ok' }
            else {
                return Promise.reject(new Error(result.message))
            }
        },
        //用户手机号登录方法
        async userLogin(LoginData: LoginData) {
            let result: UserLoginResponseData = await reqLogin(LoginData);
            if (result.code == 200) {
                this.UserInfo = result.data;
                SET_TOKEN(JSON.stringify(this.UserInfo))
                return 'ok';
                //本地存储持久化用户信息

            } else {
                return Promise.reject(new Error(result.message));
            }

        },
        logout() {
            this.UserInfo = { name: '', token: '' }
            REMOVE_TOKEN();

        },
        //查询本地存储是否有信息
        queryState() {
            let timer = setInterval(() => {
                if (GET_TOKEN()) {
                    this.visable = false;
                    this.UserInfo = JSON.parse(GET_TOKEN() as string);
                    clearInterval(timer);
                }
            }, 1000)
        }
    },
    getters: {}
})
export default useUserStore